/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Solitare;

/**
 *
 * @author User
 */
import java.awt.Graphics;
import java.util.Enumeration;
import java.util.Stack;

class TablePile extends CardPile {
	TablePile(int x, int y, int c) {
		// initialize the parent class
		super(x, y);
		// then initialize our pile of cards
		for (int i = 0; i < c; i++) {
			addCard(Solitare.deckPile.pop());
		}
		// flip topmost card face up
		top().flip();
	}

	public boolean canTake(Card aCard) {
		if (isEmpty())
			return aCard.rank() == 12;
		Card topCard = top();
		return (aCard.color() != topCard.color())
				&& (aCard.rank() == topCard.rank() - 1);
	}

	public boolean includes(int tx, int ty) {
		int count=0;
		Card a[]= new Card[100];
		int z=thePile.size();
		thePile.toArray(a);
		if(!thePile.empty() && !a[z-1].faceUp()) a[z-1].flip();
		for(int i=0;i<z;i++)
		{
			if (a[i].faceUp()) count++;
		}
		// don't test bottom of card
		if (x <= tx && tx <= x + Card.width && y + (thePile.size()-count)*35 <=ty && ty<=(y+(thePile.size()-1)*35+Card.height))
			if(ty > y + (thePile.size()-1)*35) peaks=1; else
				peaks=(-ty+(y + (thePile.size()-1)*35))/35+2;
		return x <= tx && tx <= x + Card.width && y + (thePile.size()-count)*35 <=ty && ty<=(y+(thePile.size()-1)*35+Card.height);
	}

	public void select(int tx, int ty) {
		if(!Solitare.selected)
		{
		if (isEmpty())
			return;
		// if face down, then flip

		Card topCard = top();
		if (!topCard.faceUp()) {
			topCard.flip();
			return;
		}

		}
		else
		{
		// else see if any suit pile can take card
		if(Solitare.key!=1)
		{
		Card teemp[]= new Card[100];
		int r=Solitare.allPiles[Solitare.key].thePile.size();
		Solitare.allPiles[Solitare.key].thePile.toArray(teemp);
		Card topCard=teemp[r-Solitare.allPiles[Solitare.key].peaks];
		//System.out.println(teemp[0].rank());
		/*for (int i = 0; i < 4; i++)
			if (Solitare.suitPile[i].canTake(topCard)) {
				Solitare.suitPile[i].addCard(topCard);
				return;
			}*/
		// else see if any other table pile can take card
			if (Solitare.allPiles[Solitare.cur].canTake(topCard)) {
				for(int j=r-Solitare.allPiles[Solitare.key].peaks;j<r;j++) Solitare.allPiles[Solitare.cur].thePile.push(teemp[j]);
				for(int i=0;i<Solitare.allPiles[Solitare.key].peaks;i++) Solitare.allPiles[Solitare.key].pop();
				return;
			}
		} else
		{
			Card topCard=Solitare.allPiles[Solitare.key].top();
			if (Solitare.allPiles[Solitare.cur].canTake(topCard))
			{
				Solitare.allPiles[Solitare.cur].addCard(Solitare.allPiles[Solitare.key].pop());
			}
		}
		// else put it back on our pile

		}
		Card topCard = top();
		if (!topCard.faceUp()) {
			topCard.flip();
		}
	}

	public void display(Graphics g) {
		int localy = y;
		for (Enumeration e = thePile.elements(); e.hasMoreElements();) {
			Card aCard = (Card) e.nextElement();
			aCard.draw(g, x, localy);
			localy += 35;
		}
	}
}
